const eventList = {}
let cid=0
class EventChild{
    constructor({fn, isOnce, context}){
        this.fn = fn
        this.isOnce = isOnce
        this.context = context
        this._cid = cid++
    }
}
// 绑定函数
function _bind(eventName, fn, isOnce, context){
    let eventChild = new EventChild({fn, isOnce, context})
    let event = eventList[eventName]
    if(event){
        event.push(eventChild)
    }else{
        eventList[eventName] = [eventChild]
    }
}
// 绑定事件
function on(eventName, fn, context){
    return _bind(eventName, fn, 0, context)
}
// 一次绑定
function once(eventName, fn, context){
    return _bind(eventName, fn, 1, context)
}
// 触发事件
function emit(eventName, data){
    let events = eventList[eventName]
    if(!events) throw `${eventName}事件不存在`
    for(let i=0; i<events.length; i++){
        let eventChild = events[i]
        eventChild.fn.call(eventChild.context, data)
        if(eventChild.isOnce){
            console.log('删除',eventChild)
            events.splice(i--,1)
        }
    }
}

// 解除绑定事件
function off(eventName, fn){
    let eveLis = eventList[eventName]
    if(!eveLis) throw `${eventName}事件不存在`
    for(let i=0; i<eveLis.length; i++){
        if(eveLis[i].fn === fn){
            eveLis.splice(i--,1)
        }
    }
}


module.exports = {
    on,
    emit,
    once,
    off,
    events:eventList,
    EventChild
}
